<?php
namespace App\Http\Controllers\AppApi\My;

use App\Services\Admin\UserService;
use App\Services\Finance\FinanceAccountService;
use App\Services\Finance\FinanceRecordService;
use App\Services\Finance\FinanceThirdService;
use App\Utilities\Alipay;
use Illuminate\Http\Request;

class AccountController extends BaseController
{
    /**
     * 财务接口控制器
     * 制作者：九哥
     */

    protected $model;
    protected $third;
    protected $account;
    protected $record;

    public function __construct()
    {
        parent::__construct();
        $this->model = new UserService();
        $this->third = new FinanceThirdService();
        $this->account = new FinanceAccountService();
        $this->record = new FinanceRecordService();
    }

    /**
     * 账户主页
     */
    public function getIndex(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $resUser = $this->model->getUserFinance($uid);
        //账户余额
        $finance = $resUser['finance'] ? $resUser['finance'] : '0.00';
        //收益记录
        $income = $resUser['income'] ? $resUser['income'] : '0.00';
        $dataArr = array(
            'finance' => $finance,
            'income' => $income,
        );
        return $this->toJson(0,$dataArr);
    }

    /**
     * 判断绑定
     */
    public function getBind(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $model = $this->account->getBindOneByUid($uid);
        if (!$model) { return $this->toJson(-3); }
        //判断是否支付宝
        if ($model->genre!=1) { return $this->toJson(-3); }
        $dataArr = array(
            'uid' => $model->uid,
            'account' => $model->account,
        );
        return $this->toJson(0,$dataArr);
    }

    /**
     * 充值
     */
    public function setIncome(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $money = $request->money;
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        //生成本地记录
        $serial = 'MC20190727101010'.rand(1000,9999);
        $lastId = $this->third
            ->setAdd(array(
            'uid' => $uid,
            'third' => 1,
            'genre' => 1, //1充值，2提现
            'serial' => $serial,
            'money' => $money,
            'created_at' => time(),
        ));
        $quitUrl = DOMAIN.'/h5/my/account/error.html'; //退出支付
        $returnUrl = DOMAIN.'/h5/my/account/inSuccess.html'; //同步通知
        $notifyUrl = DOMAIN.'/api/my/account/alipayNotify'; //异步通知
        $alipay = new Alipay();
        $resAlipay = $alipay->makeOrder($serial,$money,$quitUrl,$returnUrl,$notifyUrl);
        $dataArr = array(
            'aliForm' => $resAlipay,
            'params' => array(
                'serial' => $serial,
            ),
        );
        return $this->toJson(0,$dataArr);
    }

    /**
     * 提现
     */
    public function setOut(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $account = $request->account;
        $money = $request->money; //提现金额
        $finance = $request->finance; //账户余额
        if (!$token) { return $this->toJson(-2); }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        if ($money > $finance) {
            return $this->toJson(-30);
        }
        //生成本地记录
        $serial = 'MC20190727101010'.rand(1000,9999);
        $lastId = $this->third
            ->setAdd(array(
                'uid' => $uid,
                'third' => 1,
                'genre' => 2, //1充值，2提现，
                'serial' => $serial,
                'money' => $money,
                'created_at' => time(),
            ));
//        $payNo = '946493655@qq.com';
//        $payName = '九哥';
        $payNo = $account;
        $payName = '';
        $remark = '美策客户提现';
        $alipay = new Alipay();
        $resAlipay = $alipay->makeOut($serial,$payNo,$payName,$money,$remark);
        if (!$resAlipay) { return $this->toJson(-28); }
        $dataArr = array(
            'serial' => $serial,
        );
        //提现成功，更新提现的支付宝账号
        $accountModel = $this->account->getBindOneByUid($uid);
        if (!$accountModel) {
            $lastId = $this->account->setAdd(array(
                'uid' => $uid,
                'genre' => 1,
                'account' => $account,
                'bind' => 2,
                'created_at' => time(),
            ));
        } else if ($accountModel->account != $account) {
            $accModify = array('account'=>$account);
            $this->account->setModify($accModify,$accountModel->id);
        } else {
        }
        return $this->toJson(0,$dataArr);
    }

    /**
     * 同步通知，充值成功
     */
    public function setSuccessIn(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $serial = $request->serial;
        $money = $request->money;
        if (!$token) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $model = $this->third->getOneBySerial($serial);
        if (!$model) { return $this->toJson(-3); }
        //判断，如果付款已经完成，则终止下面的更新
        if ($model->status==2) {
            return $this->toJson(-31);
        }
        $dataArr = array(
            'status' => 2,
        );
        $this->third->setModifyBySerial($dataArr,$serial);
        //更新可用余额
        $resFinance = $this->model->setFinanceIncome($uid,$money);
        if (!$resFinance) { return $this->toJson(-29); }
        return $this->toJson(0);
    }

    /**
     * 同步通知，提现成功
     */
    public function setSuccessOut(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $serial = $request->serial;
        $money = $request->money;
        if (!$token) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $model = $this->third->getOneBySerial($serial);
        if (!$model) { return $this->toJson(-3); }
        //判断，如果提现已经完成，则终止下面的更新
        if ($model->status==2) {
            return $this->toJson(-40);
        }
        $dataArr = array(
            'status' => 2,
        );
        $this->third->setModifyBySerial($dataArr,$serial);
        //更新可用余额
        $resFinance = $this->model->setFinanceOut($uid,$money);
        if (!$resFinance) { return $this->toJson(-29); }
        return $this->toJson(0);
    }

    /**
     * 异步通知
     * 充值成功，支付宝支付
     */
    public function setAlipayNotify()
    {
        //支付宝交易号
        $trade_no = $_POST['trade_no'];
        //商户订单号
        $out_trade_no = $_POST['out_trade_no'];
        //交易状态
        $trade_status = $_POST['trade_status'];
        //判断该笔订单是否在商户网站中已经做过处理
        if($trade_status == 'TRADE_FINISHED' ||
            $trade_status == 'TRADE_SUCCESS') {
            return false;
        }
        //判断合法性
        if (!$out_trade_no) { return false; }
        $third = $this->third->getOneBySerial($out_trade_no);
        if (!$third) { return false; }
        if ($third->status==2) { return false; }
        $dataArr = array(
            'status' => 2,
        );
        $this->third->setModifyBySerial($dataArr,$out_trade_no);
        $resFinance = $this->model->setFinanceIncome($third->uid,$third->money);
        return true;
    }

    /**
     * 历史账单
     */
    public function getHistory(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $page = isset($request->page) ? $request->page : 1;
        $operType = $request->operType;
        if (!$token || !in_array($operType,['income','out'])) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $models = $this->third->getApiIndex($operType,$page);
        if (!count($models)) { return $this->toJson(-3); }
        $dataArr = array();
        foreach ($models as $key => $model) {
            $dataArr[$key]['id'] = $model->id;
            $dataArr[$key]['typeName'] = $model->genre==1 ? '充值' : '提现';
            $dataArr[$key]['money'] = $model->money;
            $dataArr[$key]['createTime'] = date('Y-m-d H:i',$model->created_at);
        }
        return $this->toJson(0,$dataArr);
    }

    /**
     * 平台收益获取
     */
    public function getTradeList(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $page = isset($request->page) ? $request->page : 1;
        if (!$token) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $models = $this->record->getApiIndex($uid,$page);
        if (!count($models)) { return $this->toJson(-3); }
        $dataArr = array();
        foreach ($models as $key => $model) {
            $payer = $this->model->getOne($model->payer);
//            $receiver = $this->model->getOne($model->receiver);
            $dataArr[$key]['id'] = $model->id;
            $dataArr[$key]['payName'] = $payer->name;
//            $dataArr[$key]['acceptName'] = $receiver->name;
//            $dataArr[$key]['genre'] = $model->genre;
            $dataArr[$key]['genreName'] = $model->getApiGenreName();
            $dataArr[$key]['money'] = $model->money;
            $dataArr[$key]['createTime'] = date('Y-m-d H:i',$model->created_at);
        }
        return $this->toJson(0,$dataArr);
    }

    /**
     * 平台支付
     */
    public function setTrade(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $accept = $request->accept; //收款人UID
        //付款方式：1订单保证金，2订单预付款，3订单余款支付，4工资发放，
        $genre = $request->genre;
        $orderId = isset($request->orderId) ? $request->orderId : 0;
        $money = $request->money; //付款金额
        if (!$token) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $resPlatPay = $this->setPlatPay($uid,$accept,$genre,$orderId,$money);
        //交易失败
        if ($resPlatPay['code']=='-1') {
            return $this->toJson(-32);
        } else if ($resPlatPay['code']=='-2') {
            return $this->toJson(-33);
        } else if ($resPlatPay['code']=='-3') {
            return $this->toJson(-34);
        } else if ($resPlatPay['code']=='-4') {
            return $this->toJson(-35);
        } else if ($resPlatPay['code']=='-5') {
            return $this->toJson(-36);
        } else {
        }
        return $this->toJson(0);
    }

    /**
     * 支付到账
     * 订单类支付
     */
    public function setTradeFinish(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $orderId = $request->orderId; //抢单ID
        $resFinish = $this->setTradeFinishBasic($orderId);
        if (!$resFinish) { return $this->toJson(-37); }
        return $this->toJson(0);
    }

    /**
     * 平台交易密码设置
     */
    public function setTradePwd(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $pwd = $request->pwd;
        $pwd2 = $request->pwd2;
        if (!$token) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $model = $this->model->getOne($uid);
        if ($model->tradePwd) { //有密码
            if ($pwd!=$model->tradePwd) {
                return $this->toJson(-38);
            }
        } else { //无密码
            if ($pwd!='123456') {
                return $this->toJson(-38);
            }
        }
        if (!is_numeric($pwd2) || strlen($pwd2)!=6) {
            return $this->toJson(-39);
        }
        $this->model->setTradePwd($uid,$pwd2);
        return $this->toJson(0);
    }
}